class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ result = [] val = 0 carry = 0 lenA = len(a) lenB = len(b) if lenA < lenB: # 注意坑:确保A比B长, 所以值长度也要交换 a, b = b, a lenA, lenB = lenB, lenA for i in range(lenA): print carry val = carry val += int(a[-(i+1)]) # 从最后一位开始取 if i < lenB: val += int(b[-(i+1)]) print val, carry carry = val // 2 val = val % 2 # 注意坑:注意这里val变化了,必须放下面 print val, carry result.append(str(val)) if carry: result.append(str(carry)) return ''.join(result[::-1])